package com.markyao.handler;

import com.alibaba.fastjson.JSON;
import com.markyao.dao.pojo.SysUser;
import com.markyao.service.LoginService;
import com.markyao.utils.UserThreadLocal;
import com.markyao.vo.ErrorCode;
import com.markyao.vo.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Component
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    LoginService loginService;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //这个拦截器只会在点击了发表文章之后才会进行...
        /*
        1.判断请求路径是否是controller方法(HandlerMethod)
        2.判断token是否为空
        3.验证token,loginService
        4.如果成功放行
         */
        if(!( handler instanceof HandlerMethod)){
            return true;
        }
        String token = request.getHeader("Authorization");
        log.info("=================request start===========================");
        String requestURI = request.getRequestURI();
        log.info("request uri:{}",requestURI);
        log.info("request method:{}",request.getMethod());
        log.info("token:{}", token);
        log.info("=================request end===========================");
        if(StringUtils.isBlank(token)){
            //写回提示未登录
            Result failed = Result.failed(ErrorCode.NO_LOGIN.getCode(), ErrorCode.NO_LOGIN.getMsg());
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().print(JSON.toJSONString(failed));
            return false;
        }
        SysUser sysUser = loginService.checkT(token);
        if(sysUser==null){
            //写回提示未登录
            Result failed = Result.failed(ErrorCode.NO_LOGIN.getCode(), ErrorCode.NO_LOGIN.getMsg());
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().print(JSON.toJSONString(failed));
            return false;
        }
        //登录验证成功直接放行
        UserThreadLocal.put(sysUser);//将用户对象放入ThreadLocal
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //在发表文章结束后才释放信息
        log.info("现在要把用户信息释放掉了..");
        UserThreadLocal.remove();//视图渲染完毕就释放
    }
}
